package com.lanyanhua.excel.exceltopdf;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author: lanyanhua
 * @date: 2021/3/26 10:32 上午
 * @Description:
 */
public class ExcelUtil {


    /**
     * 转pdf
     *
     * @param wb           excel
     * @param outputStream 输出流
     */
    public static void toPdf(XSSFWorkbook wb, OutputStream outputStream) throws Exception {
        // 最后输出
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        com.aspose.cells.Workbook we = new com.aspose.cells.Workbook(is);
        //隐藏workbook中不需要的sheet页。
        printSheetPage(we, new int[]{0});
        //转pdf
        PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//        pdfSaveOptions.setOnePagePerSheet(true);
//        pdfSaveOptions.isImageFitToPage(true);
        pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
        //写入 outputStream
        we.save(outputStream, pdfSaveOptions);
        is.close();
        os.close();
        wb.close();
    }

    /**
     * 获取license 去除水印
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = ExcelUtil.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void printSheetPage(com.aspose.cells.Workbook wb, int[] page) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null == page || page.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

}
